package com.example.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.juyixia.Activity_chatActivity;
import com.example.juyixia.MainActivity;
import com.example.juyixia.Myinfo;
import com.exanple.data.Activeinfo;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * 监听是否有活动请求的服务
 * 
 * @author Administrator
 *
 */
public class MessService extends Service {
	private boolean isRun;// 线程是否继续的标志
	private Handler handler1; // 显示当前时间线程消息处理器。
	public static final String bm = "utf-8";
	private static JSONObject activeInfo;
	private boolean isaccept;
	private String replyip;
	private String currentname;
	private String location;// 我的位置

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		isRun = true;
		// 向服务器传递坐标
		switch (Integer.parseInt(intent.getStringExtra("id"))) {
		case 1:
			location = "29.494749,106.576843";
			break;
		case 2:
			location = "29.495300,106.581111";
			break;
		case 3:
			location = "29.493586,106.581191";
			break;
		case 4:
			location = "29.496447,106.578065";
			break;
		}
		new Thread(new Runnable() {
			@Override
			// 在Runnable中，如果要让线程自己一直跑下去，必须自己定义while结构
			// 如果这个run()方法读完了，则整个线程自然死亡
			public void run() {
				// 定义一个线程中止标志

				try {

					ServerSocket serverSocket = new ServerSocket(54321);
					while (isRun) {
						Socket client = serverSocket.accept();
						BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), bm));
						String str = in.readLine();
						activeInfo = new JSONObject(str.split("？")[0]);
						replyip = activeInfo.getString("发起人ip：");
						currentname = str.split("？")[1];
						Message msg = new Message();
						handler1.sendMessage(msg);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();// 默认线程不启动，必须自己start()
		// 不停在接受线程的消息，根据消息的参数，进行处理 ，这里没有传递过来的参数
		handler1 = new Handler(new Handler.Callback() {// 这样写，就不弹出什么泄漏的警告了
			@Override
			public boolean handleMessage(Message msg) {
				 Builder builder = new Builder(getApplicationContext());
				 try {
				 builder.setTitle(
				 "活动名：" + activeInfo.getString("活动名：") + ";" + "发起人：" +
				 activeInfo.getString("发起人："));
				 builder.setMessage("计划参与者：" +
				 activeInfo.getString("参与者："));
				 builder.setNeutralButton("不参与", new OnClickListener() {
				
				 @Override
				 public void onClick(DialogInterface dialog, int which) {
				 // TODO Auto-generated method stub
				
				 }
				 });
				 builder.setNegativeButton("参与", new OnClickListener() {
				 @Override
				 public void onClick(DialogInterface dialog, int which) {
				 // TODO Auto-generated method stub
				 new Thread() {
				 public void run() {
				 try {
				
				 Socket socket = null;
				
				 // 创建Socket
				 socket = new Socket(replyip, 22222); // IP一定是本地机器的ip
				 Map<String, String> replymap=new HashMap<String, String>();
				 replymap.put("用户名", currentname);
				 replymap.put("坐标", location);
				 replymap.put("活动名",activeInfo.getString("活动名：") );
				 replymap.put("参与者", activeInfo.getString("参与者："));
				 replymap.put("allip", activeInfo.getString("allip"));
				 JSONObject replyjson=new JSONObject(replymap);
				 // 向服务器发送消息
				 PrintWriter out = new PrintWriter(new BufferedWriter(
				 new OutputStreamWriter(socket.getOutputStream(), bm)), true);
				 out.println(replyjson.toString());
				
				 out.close(); 
			                	 BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), bm));
			 					String str = reader.readLine();
			 					JSONObject rjson=new JSONObject(str);
			 						Activeinfo.activelist.add(new Activeinfo(rjson.getString("活动名：") , rjson.getString("参与者："), "2017.6.9"));
			 					
				 // 关闭Socket
				 socket.close();
				
				 } catch (Exception e) {
				 // TODO: handle exception
				
				 }
				
				 handler.sendEmptyMessage(0);// 执行完毕后给handler发送一个空消息
				 }
				
				 // 定义Handler对象
				 private Handler handler = new Handler() {
				 @Override
				 // 当有消息发送出来的时候就执行Handler的这个方法
				 public void handleMessage(Message msg) {
				 super.handleMessage(msg);
				 // 处理UI
				
				 }
				 };
				 }.start();
				 }
				 });
				 } catch (JSONException e) {
				 // TODO Auto-generated catch block
				 e.printStackTrace();
				 }
				 Dialog dialog=builder.create();
				 dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
				 dialog.show();
				return false;
			}
		});
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		isRun = false;

	}
}
